import 'package:flutter/material.dart';

class RefreshDemo extends StatefulWidget {
  RefreshDemo({Key? key}) : super(key: key);

  @override
  State<RefreshDemo> createState() => _RefreshDemoState();
}

class _RefreshDemoState extends State<RefreshDemo> {
  List list = []; //列表要展示的数据
  var citys = [
    "北京",
    "北京",
    "上海",
    "北京",
    "广东",
    "深圳",
    "北京",
    "杭州",
    "北京",
    "苏州",
    "郑州",
    "天津"
  ];
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        //达到最大滚动位置
        _loadData();
      }
    });
  }

  /**
   * 初始化list数据 加延时模仿网络请求
   */
  Future getData() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        list = List.generate(15, (i) => '哈喽,我是原始数据 $i');
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text("下拉刷新触底加载"),
      ),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView(
          controller: _scrollController,
          children: _budildList(),
        ),
      ),
    );
  }

  List<Widget> _budildList() {
    return citys.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 80,
      width: 160,
      margin: EdgeInsets.only(bottom: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.teal),
      child: Text(
        city,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return ListTile(
      title: Text(list[index]),
    );
  }

  /**
   * 下拉刷新方法,为list重新赋值
   */
  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        list = List.generate(5, (i) => '哈喽,我是新刷新的 $i');
      });
    });
  }

  Future<void> _loadData() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        citys.add("我是加载更多1");
        citys.add("我是加载更多2");
        citys.add("我是加载更多3");
        citys.add("我是加载更多4");
        citys.add("我是加载更多5");
      });
    });
  }
}
